import darkdetect
from PySide6.QtGui import QAction, QTextCursor
from PySide6.QtWidgets import (QMainWindow, QWidget, QHBoxLayout, QListWidget, QTabWidget,
                               QVBoxLayout, QPushButton, QTextEdit, QLineEdit, QInputDialog,
                               QFileDialog, QListWidgetItem, QApplication, QMessageBox)
from PySide6.QtCore import Qt
import json
from utils.path_processor import resource_path
import re


class MainWindow(QMainWindow):
    def __init__(self, view_model):
        super().__init__()
        self.view_model = view_model  # 视图模型对象
        self._init_ui()  # 初始化 UI
        self._connect_signals()  # 连接信号槽
        self._init_theme_menu()  # 初始化主题菜单

    def _init_theme_menu(self):
        """初始化主题切换菜单"""
        menu_bar = self.menuBar()  # 获取菜单栏
        theme_menu = menu_bar.addMenu("外观")  # 添加外观菜单

        # 主题选项配置
        actions = [
            ("跟随系统", "system"),
            ("深色模式", "dark"),
            ("浅色模式", "light")
        ]

        # 动态创建主题选项
        for text, theme in actions:
            action = QAction(text, self)  # 创建菜单动作
            action.triggered.connect(lambda _, t=theme: self._set_theme(t))  # 绑定主题切换事件
            theme_menu.addAction(action)  # 添加到菜单

    def _set_theme(self, theme):
        """应用主题设置"""
        config = {}
        try:
            # 读取配置文件
            with open(resource_path("config/config.json"), "r") as f:
                config = json.load(f)
        except FileNotFoundError:
            pass  # 文件不存在时忽略

        config["theme"] = theme  # 更新主题配置
        # 写入配置文件
        with open(resource_path("config/config.json"), "w") as f:
            json.dump(config, f)

        app = QApplication.instance()  # 获取应用实例
        # 确定实际应用主题
        if theme == "system":
            current_theme = "dark" if darkdetect.isDark() else "light"
        else:
            current_theme = theme

        try:
            # 加载对应主题样式表
            with open(resource_path(f"resources/styles/{current_theme}.qss"), "r") as f:
                app.setStyleSheet(f.read())  # 应用样式
        except FileNotFoundError:
            pass  # 样式文件缺失时忽略

    def _init_ui(self):
        """初始化主界面"""
        self.setWindowTitle("更好的云崽")  # 窗口标题
        self.setGeometry(100, 100, 800, 600)  # 初始窗口尺寸
        main_widget = QWidget()  # 主容器
        main_widget.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)  # 半透明背景
        main_layout = QHBoxLayout()  # 主水平布局

        # 实例列表初始化
        self._instance_list = QListWidget()
        self._update_instance_list(self.view_model.yunzai_mgr.instances)

        # 右侧标签页容器
        right_widget = QTabWidget()

        # 本体管理标签页
        manage_tab = QWidget()
        manage_layout = QVBoxLayout()

        # 操作按钮组
        btn_install = QPushButton("安装 Yunzai-Bot")
        btn_install.clicked.connect(self._install_yunzai)
        btn_update = QPushButton("更新 Yunzai-Bot")
        btn_update.clicked.connect(self._update_yunzai)
        btn_uninstall = QPushButton("卸载 Yunzai-Bot")
        btn_uninstall.clicked.connect(self._uninstall_yunzai)

        # 按钮水平布局
        btn_layout = QHBoxLayout()
        btn_layout.addWidget(btn_install)
        btn_layout.addWidget(btn_update)
        btn_layout.addWidget(btn_uninstall)

        # 终端容器初始化
        self.terminal_container = QTabWidget()
        self.terminal_container.setTabsClosable(True)  # 允许关闭标签
        self.terminal_container.tabCloseRequested.connect(self._close_terminal_tab)

        # 主终端创建
        self._main_terminal = self._create_terminal_widget()
        self.terminal_container.addTab(self._main_terminal, "主终端")

        # 布局组装
        manage_layout.addWidget(self.terminal_container)
        manage_layout.addLayout(btn_layout)
        manage_tab.setLayout(manage_layout)

        # 插件管理标签页
        plugin_tab = QWidget()
        plugin_layout = QVBoxLayout()
        self._plugin_list = QListWidget()  # 插件列表
        self._plugin_url = QLineEdit()  # 插件地址输入
        self._plugin_url.setPlaceholderText("输入插件 Git 地址")
        btn_install_plugin = QPushButton("安装插件")
        btn_install_plugin.clicked.connect(self._install_plugin)

        # 插件页布局
        plugin_layout.addWidget(self._plugin_list)
        plugin_layout.addWidget(self._plugin_url)
        plugin_layout.addWidget(btn_install_plugin)
        plugin_tab.setLayout(plugin_layout)

        # 添加标签页
        right_widget.addTab(manage_tab, "本体管理")
        right_widget.addTab(plugin_tab, "插件管理")

        # 主布局组装
        main_layout.addWidget(self._instance_list, 30)  # 左侧30%宽度
        main_layout.addWidget(right_widget, 70)  # 右侧70%宽度
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)

        # 底部控制栏
        control_widget = QWidget()
        control_layout = QHBoxLayout()
        btn_start = QPushButton("启动")
        btn_start.clicked.connect(lambda: self.view_model.start_yunzai(self._instance_list))
        btn_stop = QPushButton("停止")
        btn_stop.clicked.connect(self._stop_yunzai)
        btn_restart = QPushButton("重启")
        btn_restart.clicked.connect(self._restart_yunzai)

        # 控制栏布局
        control_layout.addWidget(btn_start)
        control_layout.addWidget(btn_stop)
        control_layout.addWidget(btn_restart)
        control_widget.setLayout(control_layout)
        self.statusBar().addPermanentWidget(control_widget)  # 添加到状态栏

    def _create_terminal_widget(self):
        """创建终端样式控件"""
        terminal = QTextEdit()
        terminal.setReadOnly(True)  # 只读模式
        terminal.setLineWrapMode(QTextEdit.LineWrapMode.WidgetWidth)  # 自动换行
        terminal.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)  # 始终显示滚动条
        # 终端样式配置
        terminal.setStyleSheet("""
            QTextEdit {
                background-color: #1E1E1E;
                color: #D4D4D4;
                font-family: 'Consolas';
                font-size: 10pt;
                border: 1px solid #3F3F3F;
            }
            QScrollBar:vertical {
                width: 12px;
                background: #2D2D2D;
            }
        """)
        return terminal

    def _connect_signals(self):
        """连接视图模型信号"""
        self.view_model.log_updated.connect(self._main_terminal.append)  # 日志更新信号
        self.view_model.instances_updated.connect(
            lambda: self._update_instance_list(self.view_model.yunzai_mgr.instances))  # 实例更新信号
        self.view_model.terminal_created.connect(self._create_process_terminal)  # 终端创建信号

    def _create_process_terminal(self, name, process):
        """创建进程终端标签页"""
        terminal = self._create_terminal_widget()
        tab_index = self.terminal_container.addTab(terminal, name)  # 添加新标签页

        def update_terminal(text):
            """更新终端内容"""
            cursor = terminal.textCursor()
            cursor.movePosition(QTextCursor.MoveOperation.End)
            cursor.insertText(text + '\n')
            terminal.setTextCursor(cursor)

        # 连接进程输出信号
        process.readyReadStandardOutput.connect(
            lambda: update_terminal(process.readAllStandardOutput().data().decode())
        )
        process.readyReadStandardError.connect(
            lambda: update_terminal(process.readAllStandardError().data().decode())
        )

        # 进程结束处理
        process.finished.connect(
            lambda: self.terminal_container.setTabText(tab_index, f"{name} (已结束)")
        )

    def _close_terminal_tab(self, index):
        """关闭终端标签页"""
        if index != 0:  # 保留主终端
            self.terminal_container.removeTab(index)

    def _update_instance_list(self, instances):
        """更新实例列表"""
        self._instance_list.clear()
        for instance in instances:
            item = QListWidgetItem(instance["name"])  # 创建列表项
            item.setData(Qt.ItemDataRole.UserRole, json.dumps(instance))  # 存储完整数据
            self._instance_list.addItem(item)

    def _install_yunzai(self):
        """安装Yunzai流程"""
        # 版本选择对话框
        version, ok = QInputDialog.getItem(
            self, "选择版本", "请选择版本:",
            list(self.view_model.yunzai_mgr.VERSIONS.keys()), 0, False
        )
        if not ok: return

        # 目录选择对话框
        path = QFileDialog.getExistingDirectory(self, "选择安装目录")
        if not path: return

        # 实例命名对话框
        name, ok = QInputDialog.getText(
            self, "实例名称", "请输入唯一名称:",
            text=version.split("/")[-1]
        )
        if not ok or not name.strip():
            self._main_terminal.append("安装取消或名称无效")
            return

        # 调用视图模型安装
        self.view_model.install_yunzai(self, version, path, name)

    def _uninstall_yunzai(self):
        """卸载Yunzai流程"""
        current_item = self._instance_list.currentItem()
        if not current_item:
            self._main_terminal.append("[ERROR] 请先选择要卸载的实例")
            return

        # 获取实例信息
        instance = json.loads(current_item.data(Qt.ItemDataRole.UserRole))
        name = instance["name"]
        path = instance["path"]

        # 二次确认对话框
        confirm = QMessageBox.warning(
            self,
            "危险操作确认",
            f"确定要删除这个实例吗？\n“{name}”将会永久消失（真的很久！）",
            QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel,
            QMessageBox.StandardButton.Cancel
        )

        if confirm == QMessageBox.StandardButton.Ok:
            self.view_model.uninstall_yunzai(name, path)

    # 以下为待实现功能的占位方法
    def _on_install_clicked(self):
        pass

    def _update_yunzai(self):
        pass

    def _install_plugin(self):
        pass

    def _on_install_complete(self, path, version):
        pass

    def _stop_yunzai(self):
        pass

    def _restart_yunzai(self):
        pass